//
//  NMTimer.swift
//  NetEaseMusic
//
//  Created by SAGESSE on 2020/5/30.
//  Copyright © 2020 SAGESSE. All rights reserved.
//

import UIKit

class NMAlarm {

    var extra: Any?
    
    var seconds: Int = 0
    var remaining: Int = 0
    
    func stop() {
        
    }
}
class NMTimer {
    
    init(timeInterval interval: TimeInterval, repeats: Bool = false, extra: Any? = nil, block: @escaping (NMTimer) -> Void) {
        self.block = block
        self.fireDate = .init()
        self.repeats = repeats
        self.extra = extra
        self.fire()
    }
    deinit {
        self.invalidate()
    }
    
    func fire() {
        guard timing == nil else {
            return
        }
        let timer = Timer(timeInterval: 1, target: NMTimer.self, selector: #selector(NMTimer.ticking(_:)), userInfo: self, repeats: true)
        timing = timer
        fireDate = .init()
        RunLoop.main.add(timer, forMode: .common)
        timer.fire()
    }
    func invalidate() {
        guard timing != nil else {
            return
        }
        timing?.invalidate()
        timing = nil
    }
    
    static func countdown(_ seconds: TimeInterval, with extra: Any? = nil, block: @escaping (TimeInterval) -> Void) -> NMTimer {
        return NMTimer(timeInterval: 1, repeats: true, extra: extra) {
            let remaining = $0.fireDate.timeIntervalSince(.init())
            $0.remaining = seconds + remaining
            block($0.remaining)
        }
    }

    var fireDate: Date

    var extra: Any?
    var remaining: TimeInterval = 0
    
    private var repeats: Bool
    private var timing: Timer?
    private var block: ((NMTimer) -> ())?
        
    @objc
    private class func ticking(_ timer: Timer) {
        if let timer = timer.userInfo as? NMTimer {
            timer.block?(timer)
        }
    }
}


